#!/usr/bin/env python
# @file parse_context.py


import os
import sys
import logging


class DoneParsing(Exception):
    pass


class ParseContext:

    def __init__(self, context):
        self._context = context
        self._output_buffer = []
        logging.info('ParseContext created')

    def append_output(self, msg):
        self._output_buffer += [msg]
        logging.info('%s appended output: %s' % (classname(self), msg))

    def write_error(self, msg):
        os.write(sys.stderr.fileno(), _('error: %s' % msg))

    def flush(self):
        if self._output_buffer:
            self._pp_init(0)

        for i in range(1, len(self._output_buffer)):
            if isinstance(self._output_buffer[i],
                          self._output_buffer[i-1].__class__):
                self._pp_append(i)
            else:
                self._pp_init(i)

        self._output_buffer = []

    def write_output(self, msg):
        """Writes a given message out to the terminal."""
        os.write(sys.stdout.fileno(), msg)

    def _pp_init(self, idx):
        self._write_header(idx)
        self._pp_append(idx)

    def _pp_append(self, idx):
        self.write_output(self._output_buffer[idx])

    def _write_header(self, idx):
        logging.warning('%s write_header not implemented' % classname(self))
